//
//  NSString+SizeFont.m
//  FanXing
//
//  Created by Wilson on 14/12/13.
//  Copyright (c) 2014年 kugou. All rights reserved.
//

#import "NSString+FASizeFont.h"

@implementation NSString (FASizeFont)
- (CGSize)fa_sizeWithFont:(UIFont *)font andSize:(CGSize)cSize{
    CGSize size=CGSizeZero;
    size = [self sizeWithFont:font constrainedToSize:cSize];

    return size;
}


- (int64_t)fa_maxLengthInLimitedLength:(float)limitedlength font:(UIFont*)font size:(CGSize)size{
    
    int strLength = (int)(self.length);//字符串长度
    if (limitedlength <=0  || font == nil || CGSizeEqualToSize(size, CGSizeZero)|| strLength <=0) {
        return 0;
    }
    int start = 0;
    int end = strLength;
    
    int rtnIndex = -1;
    
    while (start <= end) {
        
        if (start >= end) {
            rtnIndex = end;
            break;
        }
        
        int mid = (start + end)/2;
        
        if (mid >= strLength) {//容错
            rtnIndex = strLength;
            break;
        }
        NSString *str = [self substringToIndex:mid];
        float strWitdh = [str fa_sizeWithFont:font andSize:size].width;//当前截取字符串长度
        if (strWitdh > limitedlength) {
            end = mid - 1;
            if (end <= 0) {
                rtnIndex = 0;
                break;
            }
        }else if(strWitdh < limitedlength) {
            start = mid + 1;
            if (start >= strLength) {
                rtnIndex = strLength;
                break;
            }
        }else{
            rtnIndex = mid;
            break;
        }
    }
    
    if (rtnIndex == -1) {
        rtnIndex = end;
    }
    
    if (rtnIndex >= strLength) {
        rtnIndex = strLength ;
    }
    
    if (rtnIndex <= 0) {
        rtnIndex = 0;
    }
    
    //这里可能比实际的后一位，所以最后要做比较处理
    NSString *str = [self substringToIndex:rtnIndex];
    float strWitdh = [str fa_sizeWithFont:font andSize:size].width;//当前截取字符串长度
    if (strWitdh > limitedlength) {
        rtnIndex --;
        if (rtnIndex <=0) {
            rtnIndex = 0;
        }
    }
    
    return rtnIndex;
}

@end
